package com.app.twth.net;

import android.util.Log;

import com.app.twth.bean.BaseResponseEntity;
import com.google.gson.Gson;

import java.io.IOException;
import java.lang.reflect.Type;

import okhttp3.Response;
import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * Created by admin on 2024/5/23.
 * Description:
 * Encoding: utf-8
 */
public class GsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private final Gson gson;
    private final Type type;


    public GsonResponseBodyConverter(Gson gson, Type type) {
        this.gson = gson;
        this.type = type;
    }

    @Override
    public T convert(ResponseBody body) throws IOException {
//        if (body == null) return null;
//        Gson gson = new Gson();
//        JsonReader reader = new JsonReader(body.charStream());
//        Type genType = getClass().getGenericSuperclass();
//        Type type = ((ParameterizedType) genType).getActualTypeArguments()[0];
//        T data = gson.fromJson(reader, type);
//        return data;
//        BaseResponseEntity baseResponseEntity = gson.fromJson(body.toString(), BaseResponseEntity.class);
//        return (T) baseResponseEntity;

        String response = body.string();
        //先将返回的json数据解析到Response中，如果code==200，则解析到我们的实体基类中，否则抛异常
        Response httpResult = gson.fromJson(response, Response.class);
        Log.e(">>>>", "httpResult.code():" + httpResult.code());
        if (httpResult.code() == 200) {
            //200的时候就直接解析，不可能出现解析异常。因为我们实体基类中传入的泛型，就是数据成功时候的格式
            return gson.fromJson(response, type);
        } else {
            BaseResponseEntity baseResponseEntity = gson.fromJson(body.toString(), BaseResponseEntity.class);
            return (T) baseResponseEntity;
        }
    }
}